import {
  DeleteOutlined,
  DownOutlined,
  EditOutlined,
  PlusOutlined,
  UpOutlined,
} from '@ant-design/icons';
import { ProTable } from '@ant-design/pro-components';
import { Button, message, Tag } from 'antd';
import { useEffect, useRef, useState } from 'react';
import PopconfirmButton from '@/components/PopconfirmButton';
import { useStatusDictsModel } from '@/models/dicts';
import { buildMenuTree } from '@/models/menu';
import { delMenu, getMenuList } from '@/services/menu';
import AddModel from './AddModel';

const App = () => {
  const [parentId, setParentId] = useState<string | number | undefined>(
    undefined,
  );
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const myTable = useRef<any>(null);
  const [open, setOpen] = useState<boolean>(false);
  const [menuId, setMenuId] = useState<string | number | undefined>(undefined);
  // const [pageNum, setPageNum] = useState<number>(1);
  // const [pageSize, setPageSize] = useState<number>(defaultPageSize);
  const { statusOptions } = useStatusDictsModel();
  const [menuIds, setMenuIds] = useState<number[]>([]);
  const [isExpanded, setIsExpanded] = useState<boolean>(false);
  const [expandedRowKeys, setExpandedRowKeys] = useState<number[]>([]);
  const columns = [
    //菜单名称
    {
      title: '菜单名称',
      dataIndex: 'menuName',
      key: 'menuName',
    },
    //图标
    // {
    //   title: "图标",
    //   dataIndex: "icon",
    //   key: "icon",
    //   search: false,
    // },
    //排序
    {
      title: '排序',
      dataIndex: 'orderNum',
      key: 'orderNum',
      search: false,
    },
    //组件路径
    {
      title: '组件路径',
      dataIndex: 'path',
      key: 'path',
      search: false,
    },
    //状态
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      valueType: 'select',

      valueEnum: statusOptions.reduce(
        (prev, curr) => {
          prev[curr.value] = { text: curr.label };
          return prev;
        },
        {} as Record<string, { text: string }>,
      ),
      render: (_: any, record: any) => {
        return (
          <Tag color={record.status === '0' ? 'green' : 'red'}>
            {
              statusOptions.find((option) => option.value === record.status)
                ?.label
            }
          </Tag>
        );
      },
    },
    //创建时间
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      search: false,
    },
    //操作
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 260,
      render: (_: any, record: any) => [
        <Button
          onClick={() => {
            setOpen(true);
            setIsEdit(false);
            setMenuId(record.menuId);
            setParentId(record.menuId);
          }}
          size="small"
          type="link"
          icon={<PlusOutlined />}
          key="add"
        >
          新增
        </Button>,
        <Button
          onClick={() => {
            setOpen(true);
            setIsEdit(true);
            setParentId(record.parentId);
            setMenuId(record.menuId);
          }}
          size="small"
          type="link"
          icon={<EditOutlined />}
          key="edit"
        >
          修改
        </Button>,
        <PopconfirmButton
          key="delete"
          icon={<DeleteOutlined />}
          size="small"
          type="link"
          danger={false}
          title={`确定删除 " ${record.menuName} " 吗？`}
          onConfirm={async () => {
            const { success } = await delMenu(record.menuId);
            if (success) {
              message.success('删除成功');
              myTable.current?.reload();
            } else {
              message.error('删除失败');
            }
          }}
        >
          删除
        </PopconfirmButton>,
      ],
    },
  ];
  useEffect(() => {}, []);
  return (
    <>
      <ProTable
        actionRef={myTable}
        expandable={{
          defaultExpandAllRows: false,
          expandedRowKeys,
          onExpandedRowsChange: (expandedRows) => {
            setExpandedRowKeys(expandedRows as number[]);
          },
        }}
        rowKey={'menuId'}
        columns={columns}
        toolBarRender={() => [
          <Button
            size="small"
            ghost
            onClick={() => {
              setOpen(true);
              setIsEdit(false);
              setParentId(undefined);
              setMenuId(undefined);
            }}
            key="button"
            icon={<PlusOutlined />}
            type="primary"
          >
            新建
          </Button>,
          // 展开
          <Button
            size="small"
            onClick={() => {
              if (isExpanded) {
                setExpandedRowKeys([]);
                setIsExpanded(false);
              } else {
                setExpandedRowKeys(menuIds);
                setIsExpanded(true);
              }
            }}
            key="expand"
            icon={isExpanded ? <UpOutlined /> : <DownOutlined />}
          >
            {isExpanded ? '收起' : '展开'}
          </Button>,
        ]}
        pagination={false}
        // pagination={{
        //   showSizeChanger: true,
        //   showQuickJumper: true,
        //   pageSize: pageSize,
        //   current: pageNum,
        //   onChange: (page, size) => {
        //     setPageNum(page);
        //     setPageSize(size);
        //   },
        // }}
        request={async (params) => {
          const { data } = await getMenuList(params);
          const menuIds = data?.map((item: any) => item.menuId);
          const menuTree = buildMenuTree(data);
          // setExpandedRowKeys(menuIds);
          setMenuIds(menuIds);
          // console.log(data);
          return {
            data: menuTree,
            total: data.length,
            success: true,
          };
        }}
      />
      {open ? (
        <AddModel
          isEdit={isEdit}
          parentId={parentId as any}
          menuId={menuId as any}
          onClose={() => {
            setParentId(undefined);
            setMenuId(undefined);
            setOpen(false);
            myTable.current?.reload();
          }}
        />
      ) : null}
    </>
  );
};
export default App;
